package com.hgd.security.evp.biz.interceptor;

import com.hgd.security.evp.biz.biz.NetLogBiz;
import com.hgd.security.evp.biz.entity.NetLog;
import com.hgd.security.evp.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author By 尚
 * @date 2019/4/7 23:15
 */
@Component
public class NetAddressInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private NetLogBiz netLogBiz;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

        String remoteAddr = request.getRemoteAddr();
        String remoteHost = request.getRemoteHost();
        String remoteUser = request.getRemoteUser();
        StringBuffer requestURL = request.getRequestURL();
        int remotePort = request.getRemotePort();
        int serverPort = request.getServerPort();
        int localPort = request.getLocalPort();

        if(StringUtil.endsWith(requestURL, "login")){
            NetLog netLog =
                new NetLog(requestURL.toString(), remoteAddr, remoteHost, remoteUser, remotePort, serverPort, localPort,
                    new Date());

            try {
                netLogBiz.insertSelectiveBindCrt(netLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
